package processor

import (
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"

	"github.com/clebeg/gochat/client/manager"
	"github.com/clebeg/gochat/protocol"
	"github.com/clebeg/gochat/utils"
)

// 客户端聊天处理器
type ChatProcessor struct {
	Conn net.Conn
}

// 用户登录提示输入
func getGroupInputParams() (chatData string, err error) {
	fmt.Printf("请输入聊天内容：")
	in := bufio.NewReader(os.Stdin)
	chatData, err = in.ReadString('\n')
	if err != nil {
		err = fmt.Errorf("输入聊天内容有误，%s", err)
		return
	}
	return
}

func (c *ChatProcessor) DoGroupChat() (err error) {
	chatData, err := getGroupInputParams()

	if err != nil {
		return
	}

	reqMsg := protocol.ChatMsgReq{
		SendUserName:    manager.CurLoginUser,
		ChatData:        chatData,
		ReceiveUsername: 0,
	}

	jsonBytes, err := json.Marshal(reqMsg)

	if err != nil {
		err = fmt.Errorf("json.Marshal(reqMsg) err, err msg=%v", err)
		return
	}

	transfer := utils.Transfer{
		Conn: c.Conn,
	}

	err = transfer.SendMsg(jsonBytes, protocol.ChatMsgType)

	if err != nil {
		return
	}

	return
}

// 用户登录提示输入
func getOneInputParams() (username int, chatData string, err error) {
	fmt.Printf("请输入你想私聊的用户：")
	_, err = fmt.Scanf("%d\n", &username)
	if err != nil {
		err = fmt.Errorf("输入用户名有误，用户名只能是整数: %s", err)
		return
	}
	fmt.Printf("请输入聊天内容：")
	in := bufio.NewReader(os.Stdin)
	chatData, err = in.ReadString('\n')
	if err != nil {
		err = fmt.Errorf("输入聊天内容有误，%s", err)
		return
	}
	return
}

func (c *ChatProcessor) DoOneChat() (err error) {
	username, chatData, err := getOneInputParams()

	if err != nil {
		return
	}

	reqMsg := protocol.ChatMsgReq{
		SendUserName:    manager.CurLoginUser,
		ChatData:        chatData,
		ReceiveUsername: username,
	}

	jsonBytes, err := json.Marshal(reqMsg)

	if err != nil {
		err = fmt.Errorf("json.Marshal(reqMsg) err, err msg=%v", err)
		return
	}

	transfer := utils.Transfer{
		Conn: c.Conn,
	}

	err = transfer.SendMsg(jsonBytes, protocol.ChatMsgType)

	if err != nil {
		return
	}

	return
}
